package com.company.app.services;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingWorker;

public class LoadGifHandler {
  public JLabel showGifImage(JLabel imageLabel, String imagePath, File imageFile) {
    // 通过SwingWorker将图片加载和显示的逻辑放在单独的线程中来改善性能
    SwingWorker<BufferedImage, Void> worker = new SwingWorker<BufferedImage, Void>() {
      @Override
      protected BufferedImage doInBackground() throws Exception {
        // 打印 doInBackground() 所在的线程 ID
        System.out.println(this + ".doInBackground.ThreadID=" + Thread.currentThread().getId());
        loadGif(imageLabel, imagePath); // 处理 GIF 图片
        return ImageIO.read(imageFile); // 返回读取到的图片
      }

      @Override
      protected void done() {// 再执行
        try {
          System.out.println(this + ".showGifImage.done.ThreadID=" + Thread.currentThread().getId());
        } catch (Exception ex) {
          System.out.println(this + " Error loading image:" + ex.getMessage());
        }
      }
    };

    worker.execute();
    return imageLabel;
  }

  public void loadGif(JLabel imageLabel, String filePath) throws IOException {
    System.out.println(this + " loadGif:filePath: " + filePath);
    imageLabel.removeAll();
    displayGif(filePath, imageLabel);
    imageLabel.revalidate();
    imageLabel.repaint();
  }

  public void displayGif(String imagePath, JLabel gifLabel) {
    ImageIcon imageIcon = createImageIcon(imagePath);
    if (imageIcon != null) {
      gifLabel.setIcon(imageIcon);
      gifLabel.setHorizontalAlignment(JLabel.CENTER); // 水平居中
    } else {
      System.out.println(this + " imageLabel: Failed to open GIF image.");
    }
  }

  public ImageIcon createImageIcon(String imagePath) {
    try {
      File imageFile = new File(imagePath);
      URL imageUrl = imageFile.toURI().toURL();
      return new ImageIcon(imageUrl);
    } catch (MalformedURLException e) {
      e.printStackTrace();
      return null;
    }
  }
}